package net.NingXiaRuiTai.ShortChain.server.impl;

import com.alibaba.cloud.commons.lang.StringUtils;
import lombok.extern.slf4j.Slf4j;
import net.NingXiaRuiTai.ShortChain.component.SmsComponent;
import net.NingXiaRuiTai.ShortChain.config.SmsConfig;
import net.NingXiaRuiTai.ShortChain.constant.RedisKey;
import net.NingXiaRuiTai.ShortChain.enums.BizCodeEnum;
import net.NingXiaRuiTai.ShortChain.enums.SendCodeEnum;
import net.NingXiaRuiTai.ShortChain.server.NotifyServer;
import net.NingXiaRuiTai.ShortChain.utils.CheckUtil;
import net.NingXiaRuiTai.ShortChain.utils.CommonUtil;
import net.NingXiaRuiTai.ShortChain.utils.JsonData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.concurrent.TimeUnit;

@Service//服务层
@Slf4j
public class NotifyServerImpl implements NotifyServer {
    //验证码十分钟有效
    private  static  final int  CODE_EXPIRED=60*1000*10;

    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private SmsComponent smsComponent;
    @Autowired
    private SmsConfig smsConfig;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;


    @Override
    public JsonData sendCode(SendCodeEnum sendCodeEnum, String toPhone) {
        //存储验证码过期时间的key
        String cacheKey= String.format(RedisKey.CHECK_CODE_KEY,sendCodeEnum.name(),toPhone);
        //从redis中获取验证码
        String cacheValue = stringRedisTemplate.opsForValue().get(cacheKey);
        //判断验证码是否存在
        if (StringUtils.isNotBlank(cacheValue)) {
            //在判断是否是在60s内重复发送
            //首先按照格式分割出时间戳
            Long ttl = Long.parseLong(cacheValue.split("_")[1]);
            //当前时间戳减去验证码发送时间戳
           long liveTime=CommonUtil.getCurrentTimestamp()-ttl;
            if(liveTime<60*1000){
                log.info("验证码发送过于频繁，请{}秒后再试",liveTime);
                return JsonData.buildResult(BizCodeEnum.CODE_LIMITED);
            }
        }
    //生成拼接验证码

        //生成6位随机验证码
        String code = CommonUtil.getRandomCode(6);
        //按照redis里预定好的格式拼接验证码
        String checkCode = code + "_" + CommonUtil.getCurrentTimestamp();
        //将验证码存储到redis中
        stringRedisTemplate.opsForValue().set(cacheKey,checkCode,CODE_EXPIRED, TimeUnit.MILLISECONDS);
        if (CheckUtil.isEmail(toPhone)) {
            //发送邮箱验证码

        } else {
            //发送短信验证码
            String enCodedUrl = null;
            String minute=":5";
            try {

                enCodedUrl="**code**" + URLEncoder.encode(":"+code, "UTF-8")+","+"**minute**"+URLEncoder.encode(minute, "UTF-8");
                log.info("enCodedUrl:{}",enCodedUrl);
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            smsComponent.sendSms(toPhone,smsConfig.getTemplateId(),smsConfig.getSmsSignId(),enCodedUrl);
        }


        return JsonData.buildSuccess();
    }

    @Override
    public boolean checkCode(SendCodeEnum sendCodeEnum, String toPhone, String code) {
        //存储验证码过期时间的key
        String cacheKey= String.format(RedisKey.CHECK_CODE_KEY,sendCodeEnum.name(),toPhone);
        //从redis中获取验证码
        String cacheValue = stringRedisTemplate.opsForValue().get(cacheKey);
        //判断验证码是否存在
        if (StringUtils.isNotBlank(cacheValue)) {
            String cacheCode = cacheValue.split("_")[0];
            if(cacheCode.equals(code)){
                //删除redis中的验证码
                stringRedisTemplate.delete(cacheKey);
                return true;
            }

        }



        return false;
    }


}
